package com.hundsun.yr.universal.p2p.ui.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.Utils.HeaderMap;
import com.hundsun.yr.universal.library.base.BaseWebActivity;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils.NetType;
import com.hundsun.yr.universal.library.utils.MathUtils;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.library.widget.HSEditText;
import com.hundsun.yr.universal.p2p.bean.AdSlideBeen;
import com.hundsun.yr.universal.p2p.bean.ListOfCashBean;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.InitializePresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseActivity;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.view.base.InitializeView;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import static com.hundsun.yr.universal.p2p.ui.activity.LendActivity.formatDouble3;

/**
 * @version V1.0
 * @Title: WithDrawActivity.java
 * @Description: 出借人提现页面
 * @date 2016-1-18 下午5:32:25
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class WithDrawActivity extends BaseActivity implements OnClickListener, InitializeView,
        HSDialog.HSDialogOnItemClickListener {
    /**
     * 提交按钮
     **/
    private HSButton btn_submit = null;
    /**
     * 全额按钮
     **/
    private HSButton btn_full = null;
    /** 手续费 **/
//	private TextView tv_counterfee = null;
    /**
     * 提现金额
     **/
    private HSEditText et_money = null;

    /**
     * 请求接口
     **/
    private RequestPresenter mPresenter = null;
    /**
     * 提现公式点击区域
     **/
//	private View lay_question;
    private String canUseMoney = null;
    private String cardNo = null;
    /**
     * 可提取金额
     */
    private TextView tv_extractable_amount = null;

    /**
     * 重新签约
     *
     * @return
     */
    private HSDialog againSingDialog;

    /**
     * 提现费用
     *
     * @return
     */
    private TextView lent_server;
    private String zwgt_data;
    private ListOfCashBean bean;
    private TextView LentAccount;
    private LinearLayout lytixian;

    @Override
    protected boolean isApplyKitKatTranslucency() {

        return true;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_with_draw;
    }

    @Override
    protected void initViewsAndEvents() {

        setToolbarTitle(R.string.account_withdraw);
        et_money = findView(R.id.et_money);
        tv_extractable_amount = findView(R.id.lent_balance);
        lent_server = findView(R.id.lent_server);
        cardNo = sharedPreferences.getShareProf(UserInfo.BANKCARD);
        canUseMoney = sharedPreferences.getShareProf(UserInfo.CAN_USE_MONEY);
        btn_full = findView(R.id.btn_full);
        LentAccount = findView(R.id.lent_account);
        lytixian = findView(R.id.ly_tixian);
        btn_full.setOnClickListener(this);
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter = new InitializePresenterImpl(this, this);


        et_money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {

                if (s.length() > 0) {
                    Double fee = Double.valueOf(s.toString().trim()) * Double.valueOf(bean.getCharge_rate());
                    if (fee < Double.valueOf(bean.getMin_charge())) {
                        fee = Double.valueOf(bean.getMin_charge());
                    }
                    lent_server.setText(fee + "");
                    if (!bean.isCharge()) {
                        fee = 0.00;
                    }
                    Double withdrawFee = (Double.valueOf(s.toString().trim()) - Double.valueOf(fee));
                    if (withdrawFee < 0) {
                        withdrawFee = 0.00;
                    }
                    LentAccount.setText(formatDouble3(withdrawFee));
                } else {
                    lent_server.setText("0");
                    LentAccount.setText("0");
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(R.id.common_toolbar).init();
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
    }

    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected View getLoadingTargetView() {
        return null;
    }

    @Override
    protected void onNetworkConnected(NetType type) {
    }

    @Override
    protected void onNetworkDisConnected() {
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return true;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case linear_bankcard:// 选择银行卡
//                readyGo(MineBankCardActivity.class);
//                break;

            case R.id.btn_submit:// 提交
                validate();
                break;

            case R.id.btn_full:// 全额
                if (!TextUtils.isEmpty(bean.getList().get(0).getWithdraw().trim())) {
                    if (MathUtils.compare(bean.getList().get(0).getWithdraw().trim(), "50000") > 0) {
                        et_money.setText("50000");
                    } else {
                        et_money.setText(bean.getList().get(0).getWithdraw().trim());
                    }
                }
                break;

            default:
                break;
        }

    }

    /**
     * 本地验证
     */
    public void validate() {
// TODO: 2017/5/9 开始选择银行卡
/*		if (TextUtils.isEmpty(tv_bank.getText())) {
			showToast(R.string.input_choose_bankcard);
			return;
		}*/

        if (TextUtils.isEmpty(et_money.getText())) {
            showToast(R.string.input_withdraw_money);
            return;
        }

        if (et_money.getText().toString().endsWith(".")) {
            showToast(R.string.input_correct_number);
            return;
        }

        if (MathUtils.compare(et_money.getText().toString(), "0") <= 0) {
            showToast(R.string.min_withdraw_money);
            return;
        }

        if (MathUtils.compare(et_money.getText().toString(), bean.getMax()) > 0) {
            showToast("单笔提现金额不能超过" + bean.getMax() + "元");
            return;
        }
        if (Double.valueOf(et_money.getText().toString().trim()) < Double.valueOf(bean.getMin())) {
            showToast("单笔提现金额不能低于" + bean.getMin() + "元");
            return;
        }
        if (Double.valueOf(tv_extractable_amount.getText().toString().trim()) < Double.valueOf(bean.getMin())) {
            showToast("账号余额不足");
            return;
        }
        /**
         * 提现前判断
         */
//        againSingDialog = new HSDialog(getString(R.string.tips), "应收费用标准超出缴费授权金额，请重新签订缴费授权。", "暂不签约",
//                "重新签约", mContext, this).setCancelable(false);
//        againSingDialog.show();
        /**
         * 进行提现
         */
        String zwgt_data = BaseRequestTool2.getFormatedDateString();
        JSONObject map = new JSONObject();
        try {
            map.put("amount", LentAccount.getText().toString().trim());
            map.put("txfee", "");
            map.put("uuid", "");
            map.put("charge", lent_server.getText().toString().trim());
            map.put("total_amount", et_money.getText().toString().trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
        mPresenter.loadingData(TaskConstants.TASK_NEWWITHDRAW, getString(R.string.root_url_test) + getString(R.string.api_trade_test) + TaskConstants.TASK_NEWWITHDRAW,
                Constants.EVENT_UNCOLSEPROGRESS, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, getString(R.string.api_trade_test) +
                        TaskConstants.TASK_NEWWITHDRAW, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
    }

    /**
     * 网络成功v层的回调
     *
     * @param task_name 任务名称
     * @param data      返回数据
     * @param <T>
     */
    @SuppressWarnings("deprecation")
    @Override
    public <T> void initializeViews(String task_name, T data) {

        if (TextUtils.equals(task_name, TaskConstants.TASK_NEWWITHDRAW)) {
            String zwgt_data = BaseRequestTool2.getFormatedDateString();
            HashMap<String, String> hearder1 = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_user) +
                    "withdrawrst", sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
            HeaderMap headerMap1 = new HeaderMap();
            headerMap1.setMap(hearder1);
            Bundle bundle1 = new Bundle();
            bundle1.putString(BaseWebActivity.BUNDLE_KEY_URL, String.valueOf(data));
            bundle1.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap1);
            bundle1.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.DATA.getIntValue());
            readyGo(WebOpenAccountActivity.class, bundle1);
        } else if (TextUtils.equals(task_name, TaskConstants.TASK_CARDUNBIND)) {
            ListOfCashBean listOfCashBean = (ListOfCashBean) data;
            updateUI(listOfCashBean);
        } else if (TextUtils.equals(task_name, TaskConstants.TASK_SIGHJUST)) {
            AdSlideBeen been = (AdSlideBeen) data;
            againSingDialog = new HSDialog(getString(R.string.tips), been.getMsg(), "暂不签约",
                    "重新签约", mContext, this).setCancelable(false);
            againSingDialog.show();
        }
    }

    /**
     * 更新UI
     *
     * @param listOfCashBean
     */
    private void updateUI(ListOfCashBean listOfCashBean) {
        bean = listOfCashBean;
        Log.e("listOfCashBean",listOfCashBean.toString());
        tv_extractable_amount.setText(bean.getList().get(0).getWithdraw());
        if (!bean.isCharge()) {
            lent_server.setText("0");
//            lytixian.setVisibility(View.GONE);
        } else {
            lent_server.setText(bean.getMin_charge());
        }
    }

    @Override
    public <T> void initializeError(String task_name, T data) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("WithDrawActivity");
        MobclickAgent.onResume(this);
        mPresenter.loadingData(TaskConstants.TASK_WITHDRAEFEE, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.TASK_WITHDRAEFEE, Constants.EVENT_DATA,
                BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.TASK_WITHDRAEFEE, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.
                        getShareProf(UserInfo.TOKENID), zwgt_data), true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("WithDrawActivity");
        MobclickAgent.onPause(this);
    }

    @Override
    public void onItemClick(Object o, int position) {
        //重新签约
        if (o == againSingDialog && position != -1) {
            readyGo(ManagementActivity.class);
        }
    }
}
